<template>
  <div class="handle-container">
    <div class="box-card">
      <div class="header">
        <div class="title">
          {{ processDetailInfo?.startUser.userName }}{{ $t("workflow.flowDetail.initiateText")
          }}{{ processDetailInfo?.processName }}
        </div>
        <div class="mt10 basic-info-warp">
          <div class="item">
            <div class="s-title">{{ $t("workflow.flowDetail.statusNow") }}</div>
            <div>
              <el-tag
                :type="statusMap[processDetailInfo?.status || 0]"
                size="default"
              >
                {{ processDetailInfo?.statusDesc }}
              </el-tag>
            </div>
          </div>
          <div class="item">
            <div class="s-title">{{ $t("workflow.flowDetail.taskUser") }}</div>
            <div class="start-user-wrap mt0">
              <t-avatar
                :src="processDetailInfo?.startUser.avatar"
                :size="20"
                :name="processDetailInfo?.startUser.userName"
              />
              <span class="ml5">{{ processDetailInfo?.startUser.userName }}</span>
            </div>
          </div>
          <div class="item">
            <div class="s-title">{{ $t("workflow.flowDetail.taskUserDept") }}</div>
            <div class="mt0">{{ processDetailInfo?.startUser.deptName || $t("workflow.flowDetail.unknown") }}</div>
          </div>
          <div class="item">
            <flow-seal
              :size="100"
              v-if="processDetailInfo?.status != undefined"
              :color-type="flowStatus.get(processDetailInfo?.status || 0) || SealColorType.DEFAULT"
              :name="processDetailInfo?.statusDesc || $t('workflow.flowDetail.inReview')"
              class="flow-seal"
            />
          </div>
        </div>
      </div>
      <div class="flow-content-wrap">
        <div class="flow-form-info-wrap">
          <form-info
            v-if="!reSubmitStatus"
            ref="formInfoRef"
            class="h100"
            :task-id="taskForm.taskId"
            :instance-id="taskForm.instanceId"
          />
          <biz-project-form
            v-if="reSubmitStatus && formConfig.formKey"
            :key="taskForm.instanceId"
            ref="bizProjectFormRef"
            :form-config="formConfig"
            :form-data="formData"
            style="height: calc(100vh - 20px)"
          />
        </div>
        <div class="flow-node-timeline-wrap">
          <flow-node-timeline
            :node-list="processDetailInfo?.processTaskNodes"
            class="pl20 pt20"
          />
        </div>
      </div>
    </div>
    <div class="btn-wrap">
      <div class="flex">
        <el-button
          icon="ele-Check"
          type="success"
          @click="handleReSubmit"
          :loading="reSubmitLoading"
          v-re-click
          v-if="reSubmitStatus"
        >
          {{ $t("workflow.flowDetail.reSubmitText") }}
        </el-button>
      </div>
      <ButtonControl
        :get-form-data-id="getFormDataId"
        :get-form-model="getFormModel"
        :task-info="taskForm"
        v-if="operated == true && taskForm.taskId && !reSubmitStatus"
      />
      <div v-else>
        <el-button
          style="float: right"
          icon="ele-Back"
          type="primary"
          @click="goBack"
          v-if="!msgOpen"
        >
          {{ $t("formI18n.all.goBack") }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="ProcessHandle" lang="ts">
import type { Ref } from "vue";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import ButtonControl from "./ReviewButton.vue";
import FormInfo from "./form.vue";
import { complete, flowDetail } from "@/api/workflow/todo";
import FlowNodeTimeline from "@/views/workflow/task/process/FlowNodeTimeline.vue";
import FlowSeal from "@/views/workflow/task/process/FlowSeal.vue";
import TAvatar from "@/components/TAvatar/index.vue";
import { ProcessDetail, SealColorType } from "@/views/workflow/task/process/types";
import BizProjectForm from "@/views/formgen/components/BizProjectForm/index.vue";
import { ResultData } from "@/api/types";
import { getProcessInstanceFormData } from "@/api/workflow/workflow";
import { updateFormDataByDataIdRequest } from "@/api/project/data";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";

const router = useRouter();
const route = useRoute();

const msgOpen = ref(false);

const processDetailInfo: Ref<null | ProcessDetail> = ref(null);
const taskForm = ref({
  instanceId: "",
  deployId: "",
  taskId: "",
  procDefId: ""
});
const operated = ref(false);

const formInfoRef = ref<InstanceType<typeof FormInfo> | null>(null);

const getFormDataId = () => {
  if (!formInfoRef.value) {
    return null;
  }
  return formInfoRef.value?.formDataId;
};

const getFormModel = () => {
  if (!formInfoRef.value) {
    return null;
  }
  return formInfoRef.value?.getFormModel();
};

// 状态map
const statusMap: {
  [key: number]: string;
} = {
  1: "info",
  2: "success",
  3: "danger",
  4: "warning"
};

const flowStatus = new Map<number, SealColorType>([
  [1, SealColorType.DEFAULT],
  [2, SealColorType.SUCCESS],
  [3, SealColorType.FAIL],
  [4, SealColorType.WARNING]
]);

const getProcessDetailInfo = (procInsId: string) => {
  flowDetail({ procInsId }).then((res: any) => {
    processDetailInfo.value = res.data;
  });
};

// 重新提交状态 在打会发起人时
const reSubmitStatus = ref(false);

const formConfig = ref<any>({
  formBtns: false
});

const formData = ref<any>({});

const reSubmitLoading = ref(false);

onMounted(() => {
  taskForm.value.deployId = route.query?.deployId as string;
  taskForm.value.taskId = route.query?.taskId as string;
  taskForm.value.instanceId = route.query?.procInsId as string;
  taskForm.value.procDefId = route.query?.procDefId as string;
  operated.value = route.query?.operated == "true";
  getProcessDetailInfo(taskForm.value.instanceId);
  msgOpen.value = route.query?.msgOpen == "true";
  reSubmitStatus.value = !!route.query?.taskDefKey && route.query?.taskDefKey!.indexOf("startTask") > -1;
  if (reSubmitStatus.value) {
    getProcessInstanceFormData(taskForm.value.instanceId).then((res: ResultData) => {
      formData.value = res.data;
      formConfig.value.formKey = res.data.formKey;
    });
  }
});

const bizProjectFormRef = ref<InstanceType<typeof BizProjectForm> | null>(null);

const handleReSubmit = () => {
  bizProjectFormRef.value!.generateFormRef!.pageContentRef.validateForm().then((res: boolean) => {
    reSubmitLoading.value = true;
    if (res) {
      const formModel = bizProjectFormRef.value!.generateFormRef!.pageContentRef.formModel;
      let submitFormData = {
        originalData: bizProjectFormRef.value!.generateFormRef!.pageContentRef.formModel,
        dataId: formData.value.dataId
      };
      updateFormDataByDataIdRequest(submitFormData)
        .then(() => {
          let data = {
            ...taskForm.value,
            comment: "重新提交",
            values: formModel,
            formDataId: formData.value.id
          };
          complete(data)
            .then(() => {
              MessageUtil.success(i18n.global.t("formI18n.all.success"));
              goBack();
            })
            .finally(() => {
              reSubmitLoading.value = false;
            });
        })
        .catch(() => {
          reSubmitLoading.value = false;
        });
    }
  });
  console.log(bizProjectFormRef.value!.generateFormRef!.pageContentRef.validateForm());
};

const goBack = () => {
  router.go(-1);
};
</script>
<style lang="scss" scoped>
.handle-container {
  height: 100%;
  position: relative;
  overflow: hidden;
}

.header {
  height: 100px;
  padding: 5px 10px;
  border-bottom: var(--el-border);
  position: relative;

  .flow-seal {
    position: absolute;
    right: 20%;
    top: 30px;
    opacity: 0.4;
  }

  .title {
    margin-top: 5px;
    font-size: 18px;
    font-weight: bold;
    line-height: 25px;
    margin-left: 20px;
  }

  .s-title {
    font-size: 14px;
    line-height: 20px;
    color: var(--el-text-color-secondary);
  }

  .start-user-wrap {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
}

.btn-wrap {
  position: fixed;
  bottom: 5px;
  left: 250px;
  z-index: 888 !important;
  display: flex;
  gap: 10px;
}

.box-card {
  width: 100%;
  height: calc(100% - 60px);
  border-radius: 15px;
}
.basic-info-warp {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .item {
    width: 25%;
    text-align: center;
  }
}

.flow-content-wrap {
  display: flex;
  height: calc(100% - 60px);
  background-color: var(--el-bg-color);
  gap: 20px;

  .flow-form-info-wrap {
    width: 70%;
    height: 100%;
    padding-top: 20px;
    overflow-y: scroll;
  }

  .flow-node-timeline-wrap {
    width: 30%;
    height: calc(100% - 60px);
    overflow-y: scroll;
  }
}

@media (max-width: 768px) {
  .pagination-container .el-pagination > .el-pagination__jump {
    display: none !important;
  }
  .pagination-container .el-pagination > .el-pagination__sizes {
    display: none !important;
  }

  .flow-content-wrap {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow-y: revert !important;
  }

  .handle-container {
    overflow-y: scroll;
    background-color: var(--el-bg-color);
  }

  .flow-form-info-wrap {
    width: 100% !important;
    height: auto !important;
    padding-top: 20px;
    overflow-y: visible !important;
  }

  .flow-node-timeline-wrap {
    width: 100% !important;
    height: 95%;
    overflow-y: revert !important;
  }

  .btn-wrap {
    position: relative;
    margin-top: 10px;
    left: 0;
    width: 100%;

    :deep(.el-button) {
      width: 100%;
    }

    :deep(.el-button + .el-button) {
      margin-left: 0;
      margin-top: 5px;
    }
  }

  .header {
    height: 200px;
  }

  .basic-info-warp {
    .item {
      width: 50%;
      margin-bottom: 10px;
    }
  }

  .flow-seal {
    right: 20px !important;
    top: 82px !important;
  }

  .box-card {
    height: auto !important;
  }
}
</style>
